class DocumentsController < ApplicationController
  before_filter :login_required, :find_project
  
  def index
    @documents = @project ? @project.documents : Document.find(:all)
  end
  
  def new
    @document = Document.new
  end
  
  def create
    #project id is added for every new record
    @document = Document.new(params[:document].merge(:project_id => params[:project_id]))
    @document.name.capitalize!
    
    if @document.save
      flash[:notice] = 'Document successfully created.'
      redirect_to :action => :index
    else
      render :action => :new
    end
  end
  
  def list
    #changed to list just documents of selected project
    @documents = @project ? @project.documents : Document.find(:all)
  end

  def download
    @document = Document.find(params[:id])
    send_data(@document.data, :filename => @document.filename, :type => @document.content_type)
  end
  
  def show
    @document = Document.find(params[:id])
  end
  
  def edit
    @document = Document.find(params[:id])
    #session[:prev_page] = request.env["HTTP_REFERER"] 
    #@prev_page =  session[:prev_page].to_s
  end
  
  def update
    @document = Document.find(params[:id])
    params[:document]['name'].capitalize!
    
    
    if @document.update_attributes(params[:document])
      flash[:notice] = "Document updated successfuly"
      redirect_to :action => :list
    else
      render :action => :edit
    end  
  end
  
  def destroy
   @document = Document.find(params[:id])
   @document.destroy
   redirect_to :back
 end

 #auxilary method for listing document
 private
 def find_project
   @project = Project.find_by_id(params[:project_id])
 end
end
